﻿using System;
using System.Globalization;
using System.Linq;
using System.Web.UI;


/// <summary>
/// Public search page.
/// </summary>
public partial class Search : Page
{

	/// <summary>
	/// Event handler that is called when all controls on the page are loaded.
	/// Performs the search and displays the results on the page.
	/// </summary>
	/// <param name="sender">Sender.</param>
	/// <param name="e">Event arguments.</param>
	protected void Page_Load( object sender, EventArgs e )
	{
		// Get the keyword from query string.
		string keyword = this.Request.QueryString[ "k" ];

		if( !String.IsNullOrEmpty( keyword ) )
		{
			// Retrieve the matching song records from the database.
			HeroDataContext dc = new HeroDataContext();
			var q = from s in dc.Songs
							where s.Artist.Contains( keyword ) || s.Title.Contains( keyword )
							select new
								{
									Text = String.Format( CultureInfo.CurrentCulture, "{0}: {1}", s.Artist, s.Title ),
									Url = String.Format( CultureInfo.InvariantCulture, "~/Song.aspx?id={0}", s.ID )
								};
				
			// Display results in the datagrid.
			this.gvResults.DataSource = q;
			this.gvResults.DataBind();
		}
	}


	/// <summary>
	/// Event handler that is called when the user clicks on the Search button.
	/// Reloads the page with the search keyword in the query string.
	/// </summary>
	/// <param name="sender">Sender.</param>
	/// <param name="e">Event arguments.</param>
	protected void btnSearch_Click( object sender, EventArgs e )
	{
		// Add the search keyword to the query string.
		string url = String.Format( CultureInfo.InvariantCulture, "~/Search.aspx?k={0}", this.Server.UrlEncode( this.txtKeyword.Text ) );

		// Reload the same page with the new query string.
		this.Response.Redirect( url );
	}
}
